export class Config {
  private configObj = {
    enable: false, // enable extension or stop extension
    stopRedirect: false, // whether stop redirection
    removeIframe: false, // whether remove iframe with no video or subiframe
    removeLogs: false, //whether remove console.log
  };
  private CONFIG_KEY = "CONFIG_KEY";
  private changeCallback: (config: typeof this.configObj) => void = () => {
    // console.log("using default storage change listener");
  };
  // private inited: boolean = false;
  constructor() {
    this.listenStorageChange();
    // if (manualInit) return;
    this.initConfigFromStorage();
  }
  private listenStorageChange() {
    chrome.storage.onChanged.addListener((changes, namespace) => {
      for (let [key, { oldValue, newValue }] of Object.entries(changes)) {
        if (key !== this.CONFIG_KEY) return;
        // console.log("change_before", this.configObj);
        this.configObj = JSON.parse(newValue);
        // console.log("change_after", this.configObj);
        this.changeCallback(this.configObj);
      }
    });
  }
  private sync() {
    chrome.storage.sync.set({
      [this.CONFIG_KEY]: JSON.stringify(this.configObj),
    });
  }
  // ---------------------------------------
  private async initConfigFromStorage() {
    // if (this.inited) return Promise.resolve();
    // this.inited = true;
    return chrome.storage.sync.get([this.CONFIG_KEY]).then((data) => {
      if (!data[this.CONFIG_KEY]) return;
      // console.log(this.configObj, "init_before");
      this.configObj = JSON.parse(data[this.CONFIG_KEY]);
      // console.log(this.configObj, "init_after");
      this.changeCallback(this.configObj);
    });
  }
  public getConfig() {
    return this.configObj;
  }
  public getEnable() {
    return this.configObj.enable;
  }
  public setEnable(status: boolean) {
    this.configObj.enable = status;
    this.sync();
  }
  public getRedirect() {
    return this.configObj.stopRedirect && this.configObj.enable;
  }
  public setRedirect(status: boolean) {
    this.configObj.stopRedirect = status;
    this.sync();
  }
  public getRemoveIframe() {
    return this.configObj.removeIframe && this.configObj.enable;
  }
  public setRemoveIframe(status: boolean) {
    this.configObj.removeIframe = status;
    this.sync();
  }
  public getRemoveLogs() {
    return this.configObj.removeIframe && this.configObj.enable
  }
  public setRemoveLogs(status: boolean) {
    this.configObj.removeLogs = status
    this.sync()
  }
  public onChange(callback: typeof this.changeCallback) {
    this.changeCallback = callback;
  }
}
